﻿using Microsoft.AspNetCore.Http;
using Modules.SMS;
using Modules.SMS.Entitys;
using PmSoft;
using PmSoft.Exceptions;
using System.Net;
using System.Text;

namespace ManagementApi.TreeParty.SMS
{
    /// <summary>
    /// 乐信短信服务
    /// </summary>
    [UseDI(ServiceLifetime.Scoped, typeof(ISMSService))]
    public class LeXinSMSService : ISMSService
    {
        private readonly IConfiguration configuration;
        private readonly SmsConfigModel smsConfig = new SmsConfigModel();
        private readonly SmsSendLogService smsSendLogService;
        private readonly ILogger logger;

        public LeXinSMSService(
            IConfiguration configuration,
            SmsSendLogService smsSendLogService,
            ILogger<LeXinSMSService> logger
            )
        {
            this.smsSendLogService = smsSendLogService;
            this.configuration = configuration;
            this.logger = logger;
            smsConfig.Url = configuration.GetValue<string>("ThreePartyOptions:LeXinSms:Url");
            smsConfig.AppID = configuration.GetValue<string>("ThreePartyOptions:LeXinSms:AppID");
            smsConfig.AppSecret = configuration.GetValue<string>("ThreePartyOptions:LeXinSms:AppSecret");
        }

        public bool Send(SmsSendLog sendLog)
        {
            try
            {
                string content = sendLog.MsgContent;
                string formUrl = smsConfig.Url + "/send";
                string appID = smsConfig.AppID == null ? "" : smsConfig.AppID;
                string appSecret = smsConfig.AppSecret == null ? "" : smsConfig.AppSecret;
                //参数
                string formData = "";
                DateTime date = DateTime.Now;
                formData = formData + "&AppID=" + appID +
                  "&AppSecret=" + appSecret +
                  "&content=" + content +
                  "&aimcodes=" + sendLog.Phone +
                  "&bizId=" + string.Format("{0:yyyyMMddHHmmss}", date);
                CookieContainer cookieContainer = new CookieContainer();
                // 将提交的字符串数据转换成字节数组
                //byte[] postData = Encoding.UTF8.GetBytes(formData);
                Encoding myc = Encoding.GetEncoding("UTF-8");
                byte[] postData = myc.GetBytes(formData);
                // 设置提交的相关参数
                var request = WebRequest.Create(formUrl) as HttpWebRequest;

                Encoding myEncoding = Encoding.GetEncoding("UTF-8");
                request.Method = "POST";
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.ContentType = "application/x-www-form-urlencoded";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
                request.CookieContainer = cookieContainer;
                request.ContentLength = postData.Length;

                // 提交请求数据
                using Stream outputStream = request.GetRequestStream();
                outputStream.Write(postData, 0, postData.Length);


                using HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                using Stream responseStream = response.GetResponseStream();
                using StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
                string reStr = reader.ReadToEnd(); //返回值
                string[] msgs = reStr.Split(';');
                if (msgs.Length < 2)
                    return false;

                sendLog.Status = 1;
            }
            catch (Exception ex)
            {
                sendLog.Status = 0;
                sendLog.ResultMsg = ex.Message;
                logger.LogError(ex, "乐信短信发送异常");
            }


            smsSendLogService.Update(sendLog);

            return sendLog.Status == 1;
        }

 
    }
}
